import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_quill/flutter_quill.dart' hide Text;
import 'package:tuple/tuple.dart';

class TestDemo extends StatefulWidget {
  TestDemo({Key? key}) : super(key: key);

  @override
  _TestDemoState createState() {
    return _TestDemoState();
  }
}

class _TestDemoState extends State<TestDemo> {
  QuillController? _controller;
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _loadFromAssets();
    _clipboard();
  }

  @override
  void dispose() {
    _dispose();
    super.dispose();
  }

  // final clipboardContentStream = StreamController<String>.broadcast();
  // Stream get clipboardText => clipboardController.stream;
  late Timer clipboardTriggerTime;

  void _dispose() {
    // clipboardContentStream.close();
    clipboardTriggerTime.cancel();
  }

  _clipboard() {
    clipboardTriggerTime = Timer.periodic(
      const Duration(seconds: 5),
      (timer) {
        Clipboard.getData(Clipboard.kTextPlain).then((value) {
          print('Clipboard content ${value?.text}');
          // clipboardContentStream.add(value?.text);
        });
      },
    );
  }

  Future<void> _loadFromAssets() async {
    late Document doc;
    try {
      final result2 = [
        {
          "insert": "\n",
        }
      ];
      doc = Document.fromJson(result2);
    } catch (error) {
      print('$error');
      doc = Document()..insert(0, 'Empty asset');
    }
    setState(() {
      _controller = QuillController(
        document: doc,
        selection: const TextSelection.collapsed(offset: 0),
        onReplaceText: (int index, int len, Object? data) {
          // something changed at position index with length. data should be String.
          print("onReplaceText：$data");
          return true;
        },
        onSelectionChanged: (TextSelection selection) {
          //
          print("onSelectionChanged：$selection");
          return;
        },
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: true,
      appBar: AppBar(
        backgroundColor: Colors.grey.shade800,
        elevation: 0,
        centerTitle: false,
        title: const Text("测试"),
        actions: [
          IconButton(
            onPressed: () {
              var _text = _controller?.document.toDelta().toJson();
              // var _text = _controller?.document.toDelta();
              // var _text = _controller?.document.toPlainText();
              print('$_text');
            },
            icon: const Icon(Icons.print),
          ),
        ],
        leading: IconButton(
          icon: const Icon(
            Icons.chevron_left,
            color: Colors.white,
            size: 18,
          ),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: (_controller == null)
          ? Container()
          : GestureDetector(
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: ListView(
                padding: const EdgeInsets.all(0),
                physics: const AlwaysScrollableScrollPhysics(),
                children: [
                  const Padding(
                    padding: EdgeInsets.only(
                        top: 8, bottom: (48 - 30) / 2 + 3, left: 8, right: 8),
                    // child: Container(
                    //   height: 80,
                    //   color: Colors.grey,
                    //   child: const Text('封面图'),
                    // ),
                    child: SizedBox(
                      height: 100,
                      child: TextField(
                          maxLines: 3,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 8, right: 8),
                    child: Row(
                      children: [
                        Container(
                          color: Colors.orangeAccent.shade200,
                          width: 200,
                          child: TextButton.icon(
                            onPressed: () {
                              _addNote(context);
                              // _editNote(context);
                            },
                            icon: Icon(Icons.add),
                            label: Text("添加商品"),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 12, bottom: 12),
                    child: _buildWelcomeEditor(context),
                  ),
                  // _buildWelcomeEditor(context),
                  // Padding(
                  //   padding: EdgeInsets.only(top: 0),
                  //   child: ListView.builder(
                  //     shrinkWrap: true,
                  //     physics: NeverScrollableScrollPhysics(),
                  //     itemCount: 5,
                  //     itemBuilder: (BuildContext context, int index) {
                  //       return Container(
                  //         height: 60,
                  //         color: Color.fromARGB(255, 255 / (index + 1) ~/ 1,
                  //             index * 40, index * 30),
                  //       );
                  //     },
                  //   ),
                  // ),
                ],
              ),
            ),
    );
  }

  Widget _buildWelcomeEditor(BuildContext context) {
    return QuillEditor(
      controller: _controller!,
      scrollController: ScrollController(),
      scrollPhysics: ClampingScrollPhysics(),
      textCapitalization: TextCapitalization.none,
      scrollable: true,
      focusNode: _focusNode,
      autoFocus: false,
      readOnly: false,
      placeholder: 'Add content',
      enableSelectionToolbar: true,
      expands: false,
      padding: EdgeInsets.all(10),
      minHeight: 500,
      // onImagePaste: _onImage aste,
      // onTapUp: (details, p1) {
      //   return _onTripleClickSelection();
      // },
      customStyles: DefaultStyles(
        sizeSmall: const TextStyle(fontSize: 14),
      ),
      embedBuilders: [
        HxItemEmbedBuilder(addEditNote: _editNote),
      ],
    );
  }

  Future<void> _addNote(BuildContext context) async {
    final block = BlockEmbed.custom(
      HXItemBlockEmbed.fromDataMap({
        "price": "100",
        "title": "phoneeeeee",
      }),
    );
    final controller = _controller!;
    var index = controller.selection.baseOffset;
    var length = controller.selection.extentOffset - index;
    controller.document.insert(index, '\n');
    controller.replaceText(index, length, block, null);
    // controller.document.insert(index + 1, block.data);
  }

  Future<void> _editNote(BuildContext context, {Document? document}) async {
    final isEditing = document != null;
    final quillEditorController = QuillController(
      document: document ?? Document(),
      selection: const TextSelection.collapsed(offset: 0),
    );

    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        titlePadding: const EdgeInsets.only(left: 16, top: 8),
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('${isEditing ? 'Edit' : 'Add'} note'),
            IconButton(
              onPressed: () => Navigator.of(context).pop(),
              icon: const Icon(Icons.close),
            )
          ],
        ),
        content: QuillEditor.basic(
          controller: quillEditorController,
          readOnly: false,
        ),
      ),
    );

    if (quillEditorController.document.isEmpty()) return;

    final block = BlockEmbed.custom(
      HXItemBlockEmbed.fromDocument(quillEditorController.document),
    );
    final controller = _controller!;
    final index = controller.selection.baseOffset;
    final length = controller.selection.extentOffset - index;

    if (isEditing) {
      final offset = getEmbedNode(controller, controller.selection.start).item1;
      controller.replaceText(
          offset, 1, block, TextSelection.collapsed(offset: offset));
    } else {
      controller.replaceText(index, length, block, null);
    }
  }
}

class HxItemEmbedBuilder implements EmbedBuilder {
  HxItemEmbedBuilder({required this.addEditNote});

  Future<void> Function(BuildContext context, {Document? document}) addEditNote;

  @override
  String get key => 'noteTags';

  @override
  Widget build(
    BuildContext context,
    QuillController controller,
    Embed node,
    bool readOnly,
  ) {
    node.singleLine = true;
    return RichText(
      text: TextSpan(
          style: DefaultTextStyle.of(context).style,
          children: <InlineSpan>[
            TextSpan(text: '老孟', style: TextStyle(color: Colors.red)),
            TextSpan(text: '我是手机1111122333333333333333333333333一个有态度的程序员', style: TextStyle(color: Colors.blue),),
          ]),
    );
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.network(
          "https://img12.360buyimg.com/n1/s450x450_jfs/t1/209208/11/27998/51820/636e948fE287da1f3/ce0b08abc22372ee.jpg",
          width: 15,
          height: 15,
        ),
        const Text(
          "我是手机11111223.3333333333333333333333333",
          style: TextStyle(color: Colors.blue),
        ),
      ],
    );

    // final notes = HXItemBlockEmbed(node.value.data).document;
    return Material(
      color: Colors.white,
      child: Container(
        color: Colors.grey.shade400,
        width: 300,
        margin: EdgeInsets.only(top: 10),
        height: 100,
        child: GestureDetector(
          onLongPress: () {
            // addEditNote(context, document: notes);
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Padding(padding: EdgeInsets.only(left: 10)),
              SizedBox(
                width: 80,
                height: 80,
                child: Image.network(
                    "https://img12.360buyimg.com/n1/s450x450_jfs/t1/209208/11/27998/51820/636e948fE287da1f3/ce0b08abc22372ee.jpg"),
              ),
              Padding(padding: EdgeInsets.only(left: 10)),
              Expanded(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text("我是手机"),
                    Text("价格： 100"),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class HXItemBlockEmbed extends CustomBlockEmbed {
  static const String noteType = 'noteTags';

  const HXItemBlockEmbed(String value) : super(noteType, value);

  static HXItemBlockEmbed fromDocument(Document document) =>
      HXItemBlockEmbed(jsonEncode(document.toDelta().toJson()));

  static HXItemBlockEmbed fromDataMap(Map data) =>
      HXItemBlockEmbed(jsonEncode(data));

// Document get document => Document.fromJson(jsonDecode(data));
}
